import React, { useEffect } from 'react';
import classnames from 'classnames';
import './index.less';

export type PageProps = {
  title?: string;
  show: boolean;
  className?: string;
  onClose: () => void;
};

const Page: React.FunctionComponent<PageProps> = (props) => {
  const { children, show, title, onClose, className } = props;
  const oldTitle = document.title;

  useEffect(() => {
    const { history } = window;
    const state = history || { length: 0 };
    const { length } = state;
    if (length > 0) {
      history.go(-length);
    }

    if (show) {
      if (title) {
        document.title = title;
      }
      history.pushState(
        {
          length: 1,
        },
        title,
        document.URL,
      );
    }
  });

  const handleClose = () => {
    document.title = oldTitle;
    if (typeof onClose === 'function') {
      onClose();
    }
  };

  useEffect(() => {
    window.addEventListener('popstate', handleClose);
    return () => {
      window.removeEventListener('popstate', handleClose);
    };
  }, []);

  return <div className={classnames('hr-mini-page', className, { show })}>{show && children}</div>;
};

export default Page;
